<template>
  <div class="test-cases">
    <div class="page-header">
      <h2>测试用例管理</h2>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        创建测试用例
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card style="margin-bottom: 20px;">
      <el-form :model="searchForm" inline>
        <el-form-item label="用例名称">
          <el-input v-model="searchForm.name" placeholder="搜索用例名称" clearable />
        </el-form-item>
        <el-form-item label="用例类型">
          <el-select v-model="searchForm.case_type" placeholder="选择类型" clearable class="long-select">
            <el-option label="单接口测试" value="single" />
            <el-option label="场景测试" value="scenario" />
          </el-select>
        </el-form-item>
        <el-form-item label="环境">
          <el-select v-model="searchForm.environment" placeholder="选择环境" clearable class="long-select">
            <el-option
              v-for="env in environments"
              :key="env.id"
              :label="env.name"
              :value="env.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadTestCases">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 测试用例列表 -->
    <el-card>
      <el-table :data="testCases" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="用例名称" min-width="200" />
        <el-table-column prop="case_type" label="类型" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.case_type === 'single' ? 'primary' : 'success'">
              {{ scope.row.case_type === 'single' ? '单接口' : '场景' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="environment_name" label="环境" width="120" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'info'">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_by_username" label="创建者" width="120" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewTestCase(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="executeTestCase(scope.row)">
              执行
            </el-button>
            <el-button size="small" type="warning" @click="editTestCase(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteTestCase(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingTestCase ? '编辑测试用例' : '创建测试用例'"
      width="80%"
      top="5vh"
    >
      <el-form :model="testCaseForm" :rules="formRules" ref="testCaseFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用例名称" prop="name">
              <el-input v-model="testCaseForm.name" placeholder="请输入用例名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用例类型" prop="case_type">
              <el-select v-model="testCaseForm.case_type" placeholder="选择用例类型">
                <el-option label="单接口测试" value="single" />
                <el-option label="场景测试" value="scenario" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="测试环境" prop="environment">
          <el-select v-model="testCaseForm.environment" placeholder="选择测试环境">
            <el-option
              v-for="env in environments"
              :key="env.id"
              :label="env.name"
              :value="env.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用例描述" prop="description">
          <el-input
            v-model="testCaseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入用例描述"
          />
        </el-form-item>
        
        <el-form-item label="YAML配置" prop="yaml_content">
          <div class="yaml-editor-container wide-yaml-editor">
            <el-input
              v-model="testCaseForm.yaml_content"
              type="textarea"
              :rows="20"
              placeholder="请输入YAML配置内容"
              font-family="monospace"
            />
          </div>
          <div class="yaml-actions">
            <el-button size="small" @click="validateYaml">验证YAML</el-button>
            <el-button size="small" @click="loadYamlTemplate">加载模板</el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch v-model="testCaseForm.is_active" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="saveTestCase" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="测试用例详情" width="80%">
      <div v-if="selectedTestCase">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用例名称">{{ selectedTestCase.name }}</el-descriptions-item>
          <el-descriptions-item label="用例类型">
            {{ selectedTestCase.case_type === 'single' ? '单接口测试' : '场景测试' }}
          </el-descriptions-item>
          <el-descriptions-item label="测试环境">{{ selectedTestCase.environment_name }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ selectedTestCase.created_by_username }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedTestCase.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedTestCase.is_active ? 'success' : 'info'">
              {{ selectedTestCase.is_active ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ selectedTestCase.description }}</el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;">
          <h4>YAML配置</h4>
          <el-input
            v-model="selectedTestCase.yaml_content"
            type="textarea"
            :rows="15"
            readonly
            font-family="monospace"
          />
        </div>
        
        <div style="margin-top: 20px;" v-if="selectedTestCase.executions && selectedTestCase.executions.length">
          <h4>执行历史</h4>
          <el-table :data="selectedTestCase.executions" style="width: 100%">
            <el-table-column prop="status_display" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status_display }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="execution_time" label="执行时长" width="120">
              <template #default="scope">
                {{ scope.row.execution_time ? `${scope.row.execution_time}s` : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="执行时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button size="small" @click="viewExecutionResult(scope.row)">
                  查看结果
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { testCaseAPI, environmentAPI } from '@/api'

export default {
  name: 'TestCases',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const showCreateDialog = ref(false)
    const showDetailDialog = ref(false)
    const editingTestCase = ref(null)
    const selectedTestCase = ref(null)
    const testCases = ref([])
    const environments = ref([])
    const testCaseFormRef = ref(null)

    const searchForm = reactive({
      name: '',
      case_type: '',
      environment: ''
    })

    const testCaseForm = reactive({
      name: '',
      description: '',
      case_type: 'single',
      environment: '',
      yaml_content: '',
      is_active: true
    })

    const pagination = reactive({
      page: 1,
      page_size: 20,
      total: 0
    })

    const formRules = {
      name: [{ required: true, message: '请输入用例名称', trigger: 'blur' }],
      case_type: [{ required: true, message: '请选择用例类型', trigger: 'change' }],
      environment: [{ required: true, message: '请选择测试环境', trigger: 'change' }],
      yaml_content: [{ required: true, message: '请输入YAML配置', trigger: 'blur' }]
    }

    const loadTestCases = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          page_size: pagination.page_size,
          ...searchForm
        }
        const response = await testCaseAPI.getList(params)
        testCases.value = response.results || []
        pagination.total = response.count || 0
      } catch (error) {
        console.error('加载测试用例失败:', error)
      } finally {
        loading.value = false
      }
    }

    const loadEnvironments = async () => {
      try {
        const response = await environmentAPI.getList()
        environments.value = response.results || []
      } catch (error) {
        console.error('加载环境列表失败:', error)
      }
    }

    const resetSearch = () => {
      Object.assign(searchForm, {
        name: '',
        case_type: '',
        environment: ''
      })
      loadTestCases()
    }

    const handleSizeChange = (size) => {
      pagination.page_size = size
      loadTestCases()
    }

    const handleCurrentChange = (page) => {
      pagination.page = page
      loadTestCases()
    }

    const viewTestCase = async (testCase) => {
      try {
        const response = await testCaseAPI.getDetail(testCase.id)
        selectedTestCase.value = response
        showDetailDialog.value = true
      } catch (error) {
        console.error('获取测试用例详情失败:', error)
      }
    }

    const executeTestCase = async (testCase) => {
      try {
        await ElMessageBox.confirm(`确定要执行测试用例"${testCase.name}"吗？`, '确认执行', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await testCaseAPI.execute(testCase.id)
        ElMessage.success('测试用例执行成功')
        loadTestCases()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('执行测试用例失败:', error)
        }
      }
    }

    const editTestCase = (testCase) => {
      editingTestCase.value = testCase
      Object.assign(testCaseForm, {
        name: testCase.name,
        description: testCase.description,
        case_type: testCase.case_type,
        environment: testCase.environment,
        yaml_content: testCase.yaml_content,
        is_active: testCase.is_active
      })
      showCreateDialog.value = true
    }

    const deleteTestCase = async (testCase) => {
      try {
        await ElMessageBox.confirm(`确定要删除测试用例"${testCase.name}"吗？`, '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await testCaseAPI.delete(testCase.id)
        ElMessage.success('删除成功')
        loadTestCases()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除测试用例失败:', error)
        }
      }
    }

    const validateYaml = async () => {
      if (!editingTestCase.value) {
        ElMessage.warning('请先保存测试用例')
        return
      }
      
      try {
        const response = await testCaseAPI.validateYaml(editingTestCase.value.id)
        if (response.valid) {
          ElMessage.success('YAML配置验证通过')
        } else {
          ElMessage.error(response.message)
        }
      } catch (error) {
        console.error('验证YAML失败:', error)
      }
    }

    const loadYamlTemplate = () => {
      const template = testCaseForm.case_type === 'single' 
        ? `test_case:
  name: "示例测试用例"
  description: "这是一个示例测试用例"
  request:
    method: "POST"
    url: "http://api.example.com/login"
    headers:
      Content-Type: "application/json"
    data:
      username: "test_user"
      password: "test_password"
  assertions:
    - type: "status_code"
      expected: 200
    - type: "json_path"
      path: "$.token"
      expected: "not_empty"`
        : `scenario_test:
  name: "示例场景测试"
  description: "这是一个示例场景测试"
  steps:
    - name: "步骤1"
      request:
        method: "POST"
        url: "http://api.example.com/register"
        data:
          username: "new_user"
          password: "password123"
      assertions:
        - type: "status_code"
          expected: 201
      variables:
        user_id: "$.user_id"
    
    - name: "步骤2"
      request:
        method: "POST"
        url: "http://api.example.com/login"
        data:
          username: "new_user"
          password: "password123"
      assertions:
        - type: "status_code"
          expected: 200`
      
      testCaseForm.yaml_content = template
    }

    const saveTestCase = async () => {
      if (!testCaseFormRef.value) return
      
      try {
        await testCaseFormRef.value.validate()
        saving.value = true
        
        if (editingTestCase.value) {
          await testCaseAPI.update(editingTestCase.value.id, testCaseForm)
          ElMessage.success('更新成功')
        } else {
          await testCaseAPI.create(testCaseForm)
          ElMessage.success('创建成功')
        }
        
        showCreateDialog.value = false
        loadTestCases()
        resetForm()
      } catch (error) {
        console.error('保存测试用例失败:', error)
      } finally {
        saving.value = false
      }
    }

    const resetForm = () => {
      editingTestCase.value = null
      Object.assign(testCaseForm, {
        name: '',
        description: '',
        case_type: 'single',
        environment: '',
        yaml_content: '',
        is_active: true
      })
      if (testCaseFormRef.value) {
        testCaseFormRef.value.resetFields()
      }
    }

    const getStatusType = (status) => {
      const typeMap = {
        'passed': 'success',
        'failed': 'danger',
        'error': 'danger',
        'running': 'warning',
        'pending': 'info'
      }
      return typeMap[status] || 'info'
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }

    const viewExecutionResult = (execution) => {
      // 这里可以实现查看执行结果的逻辑
      console.log('查看执行结果:', execution)
    }

    onMounted(() => {
      loadTestCases()
      loadEnvironments()
    })

    return {
      loading,
      saving,
      showCreateDialog,
      showDetailDialog,
      editingTestCase,
      selectedTestCase,
      testCases,
      environments,
      searchForm,
      testCaseForm,
      testCaseFormRef,
      pagination,
      formRules,
      loadTestCases,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      viewTestCase,
      executeTestCase,
      editTestCase,
      deleteTestCase,
      validateYaml,
      loadYamlTemplate,
      saveTestCase,
      getStatusType,
      formatDate,
      viewExecutionResult
    }
  }
}
</script>

<style scoped>
.test-cases {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.yaml-editor-container {
  position: relative;
}

/* 新增：让 YAML 编辑器更宽 */
.wide-yaml-editor {
  width: 100%;
  max-width: 100%;
}

.yaml-editor-container .el-textarea {
  width: 100%;
  max-width: 100%;
  font-family: monospace;
  font-size: 15px;
}

.yaml-actions {
  margin-top: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.long-select {
  min-width: 220px;
  max-width: 320px;
}
</style> 